package com.mask.sca.core;

import com.alibaba.fastjson.JSONObject;
import com.mask.sca.core.entity.CurrentUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(UserInfoInterceptor.class);
    // 构造器日志：确认拦截器是否被Spring实例化
    public UserInfoInterceptor() {
        log.info("UserInfoInterceptor实例已创建");
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userInfoJson = request.getHeader("currentUserInfo");
        log.info("拦截到请求，currentUserInfo: {}", userInfoJson);
        if (userInfoJson != null) {
            try {
                CurrentUserInfo userInfo = JSONObject.parseObject(userInfoJson, CurrentUserInfo.class);
                UserContextHolder.setCurrentUser(userInfo);
                log.info("成功解析用户信息: {}", userInfo.getUserName());
            } catch (Exception e) {
                log.error("解析用户信息失败: {}", e.getMessage(), e);
                log.error("原始JSON内容: {}", userInfoJson);
            }
        } else {
            log.warn("请求头中未找到currentUserInfo");
        }
        return true;
    }
}